import FungibleToken from "../contracts/FungibleToken.cdc"
import NonFungibleToken from "../contracts/NonFungibleToken.cdc"
import FlowToken from "../contracts/FlowToken.cdc"
import NftEggsNFT from "../contracts/NftEggsNFT.cdc"
import NftEggsStore from "../contracts/NftEggsStore.cdc"

transaction(listingResourceID: UInt64, storefrontAddress: Address) {
    let paymentVault: @FungibleToken.Vault
    let NftEggsNFTCollection: &NftEggsNFT.Collection{NonFungibleToken.Receiver}
    let storefront: &NftEggsStore.Storefront{NftEggsStore.StorefrontPublic}
    let listing: &NftEggsStore.Listing{NftEggsStore.ListingPublic}

    prepare(acct: AuthAccount) {
        self.storefront = getAccount(storefrontAddress)
            .getCapability<&NftEggsStore.Storefront{NftEggsStore.StorefrontPublic}>(
                NftEggsStore.StorefrontPublicPath
            )!
            .borrow()
            ?? panic("Could not borrow Storefront from provided address")

        self.listing = self.storefront.borrowListing(listingResourceID: listingResourceID)
                    ?? panic("No Offer with that ID in Storefront")
        let price = self.listing.getDetails().salePrice

        let mainFlowVault = acct.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault)
            ?? panic("Cannot borrow FlowToken vault from acct storage")
        self.paymentVault <- mainFlowVault.withdraw(amount: price)

        self.NftEggsNFTCollection = acct.borrow<&NftEggsNFT.Collection{NonFungibleToken.Receiver}>(
            from: /storage/NFTCollection
        ) ?? panic("Cannot borrow NFT collection receiver from account")
    }

    execute {
        let item <- self.listing.purchase(
            payment: <-self.paymentVault
        )

        self.NftEggsNFTCollection.deposit(token: <-item)


        //购买成功，下架
        self.storefront.cleanup(listingResourceID: listingResourceID)
    }


}
